package com.lvmama.pangolin.controller;

import com.github.pagehelper.PageInfo;
import com.lvmama.pangolin.common.Constant;
import com.lvmama.pangolin.common.ExportExcelUtils;
import com.lvmama.pangolin.entity.LMMCareProductVO;
import com.lvmama.pangolin.entity.lmm.LMMCareProduct;
import com.lvmama.pangolin.lmm.service.LMMCareProductService;
import com.lvmama.pangolin.service.CityService;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("backConfig")
@PreAuthorize("hasAnyRole('admin')")
public class ProdConfigController {
	
	@Autowired
	LMMCareProductService productService;
	@Autowired
	private CityService cityService;
	
	@RequestMapping("prodConfig")
	public String prodConfig(ModelMap model,LMMCareProductVO pc){
		
		List<LMMCareProduct> prodList=productService.getAllList(pc);
		PageInfo<LMMCareProduct> page = new PageInfo<LMMCareProduct>(prodList);
		model.addAttribute("prodList",prodList);
		model.addAttribute("page",page);
		model.addAttribute("LMMCareProductVO", pc);
		return "background/config/prodConfig";
	}
	//UpdateCareProduct
	@RequestMapping(value = "/updateCareProduct", method = { RequestMethod.GET,
			RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> updateCareProduct(ModelMap model,String productId,String productName,String actualName,
			String cityName,String cityCode,String businessCode,String updateTime,String insertTime,
			String xc_name,String xc_url,String tc_name,String tc_url,String tn_name,String tn_url,
			String qnr_name,String qnr_url,String yl_name,String yl_url,String mt_url,String mt_name){//参数上增加美团对应字段
		
		Map<String, Object> result=getResult();
		List<String> cityIds = cityService.queryIdByName(cityName);
		if (cityIds.size() != 1) {
			result.put("cityError", "请输入正确的城市名！");
		}else{
			LMMCareProduct cp=new LMMCareProduct();
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			cp.setProductId(productId);
			cp.setProductName(productName);
			cp.setActualName(actualName);
			cp.setCityName(cityName);
			cp.setCityCode(cityIds.get(0));
			cp.setBusinessCode(businessCode);
			try {
				cp.setUpdateTime(sdf.parse(updateTime));
			} catch (ParseException e) {
				e.printStackTrace();
			}
			try {
				cp.setInsertTime(sdf.parse(insertTime));
			} catch (ParseException e) {
				e.printStackTrace();
			}
			cp.setXc_name(xc_name);
			cp.setXc_url(xc_url);
			cp.setTc_name(tc_name);
			cp.setTc_url(tc_url);
			cp.setTn_name(tn_name);
			cp.setTn_url(tn_url);
			cp.setQnr_name(qnr_name);
			cp.setQnr_url(qnr_url);
			cp.setYl_name(yl_name);
			cp.setYl_url(yl_url);
			//新增美团
			cp.setMt_url(mt_url);
			cp.setMt_name(mt_name);
			productService.updateByPrimaryKeySelective(cp);
		}
		
//		LMMCareProductVO pc=new LMMCareProductVO();
//		List<LMMCareProduct> prodList=productService.getAllList(pc);
//		PageInfo<LMMCareProduct> page = new PageInfo<LMMCareProduct>(prodList);
//		model.addAttribute("prodList",prodList);
//		model.addAttribute("page",page);
//		model.addAttribute("LMMCareProductVO", pc);
//		
//		String cityName=cp.getCityName();
//		List<String> cityIds=cityService.queryIdByName(cityName);
//		if(cityIds.size()!=1){
//			result.put("cityError","请输入正确的城市名！");
//		}else{
//			cp.setCityCode(cityIds.get(0));
//			productService.updateByPrimaryKeySelective(cp);
//		}
		
		//model.addAttribute("prodList",prodList);
		//model.addAttribute("page",page);
		//model.addAttribute("LMMCareProductVO", pc);
//		return "background/config/prodConfig";
		return result;
	}
	
	@RequestMapping(value = "/newCareProduct", method = { RequestMethod.GET,
			RequestMethod.POST })
	//@ResponseBody
	public String newCareProduct(ModelMap model,String productId,String productName,String actualName,
			String cityName,String businessCode,String updateTime,String insertTime,
			String xc_name,String xc_url,String tc_name,String tc_url,String tn_name,String tn_url,
			String qnr_name,String qnr_url,String yl_name,String yl_url,String mt_name,String mt_url){//参数上增加美团
		List<String> cityIds=cityService.queryIdByName(cityName);
		
		if(cityIds.size()!=1){
			model.addAttribute("cityError","请输入正确的城市名！");
		}else{
			LMMCareProduct  lmmProd=productService.selectByPrimaryKey(productId);
			if(lmmProd==null){
				LMMCareProduct cp=new LMMCareProduct();
				cp.setCityCode(cityIds.get(0));
				SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
				cp.setProductId(productId);
				cp.setProductName(productName);
				cp.setActualName(actualName);
				cp.setCityName(cityName);
				cp.setBusinessCode(businessCode);
				if(updateTime!=null&&updateTime.length()>0){
					try {
						cp.setUpdateTime(sdf.parse(updateTime));
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}
				if(insertTime!=null&&insertTime.length()>0){
					try {
						cp.setInsertTime(sdf.parse(insertTime));
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}
				if(xc_name!=null&&xc_name.length()>0&&xc_name.trim().length()>0){
					cp.setXc_name(xc_name);
				}
				if(xc_url!=null&&xc_url.length()>0&&xc_url.trim().length()>0){
					cp.setXc_url(xc_url);
				}
				if(tc_name!=null&&tc_name.length()>0&&tc_name.trim().length()>0){
					cp.setTc_name(tc_name);
				}
				if(tc_url!=null&&tc_url.length()>0&&tc_url.trim().length()>0){
					cp.setTc_url(tc_url);
				}
				if(tn_name!=null&&tn_name.length()>0&&tn_name.trim().length()>0){
					cp.setTn_name(tn_name);
				}
				if(tn_url!=null&&tn_url.length()>0&&tn_url.trim().length()>0){
					cp.setTn_url(tn_url);
				}
				if(qnr_name!=null&&qnr_name.length()>0&&qnr_name.trim().length()>0){
					cp.setQnr_name(qnr_name);
				}
				if(qnr_url!=null&&qnr_url.length()>0&&qnr_url.trim().length()>0){
					cp.setQnr_url(qnr_url);
				}
				if(yl_name!=null&&yl_name.length()>0&&yl_name.trim().length()>0){
					cp.setYl_name(yl_name);
				}
				if(yl_url!=null&&yl_url.length()>0&&yl_url.trim().length()>0){
					cp.setYl_url(yl_url);
				}
				//新增美团
				if(mt_name!=null&&mt_name.length()>0&&mt_name.trim().length()>0){
					cp.setMt_name(mt_name);
				}
				if(mt_url!=null&&mt_url.length()>0&&mt_url.trim().length()>0){
					cp.setMt_url(mt_url);
				}

				productService.insertSelective(cp);
			}else{
				model.addAttribute("idError","产品id不能重复！");
			}
			
		}
		
		LMMCareProductVO pc=new LMMCareProductVO();
		List<LMMCareProduct> prodList=productService.getAllList(pc);
		PageInfo<LMMCareProduct> page = new PageInfo<LMMCareProduct>(prodList);
		model.addAttribute("prodList",prodList);
		model.addAttribute("page",page);
		model.addAttribute("LMMCareProductVO", pc);
		
		return "background/config/prodConfig";
	}
	
	@RequestMapping(value = "/getCityCode", method = { RequestMethod.GET,
			RequestMethod.POST })
	@ResponseBody
    public Map<String, Object> getCityCode(String cityName){
		Map<String, Object> result=getResult();
		List<String> cityIds=cityService.queryIdByName(cityName);
		
		if(cityIds.size()!=1){
			result.put("cityError","请输入正确的城市名！");
		}else{
			result.put("cityCodes",cityIds);
		}
		return result;
       
    }
	
	
	@RequestMapping(value = "/deleteCareProduct", method = { RequestMethod.GET,
			RequestMethod.POST })
	@ResponseBody
    public void deleteCareProduct(String productId){
		
    	productService.deleteByPrimaryKey(productId);
       
    }
	
	@RequestMapping("export")
    public void exportData(LMMCareProductVO po,HttpServletResponse response,HttpServletRequest request) throws IOException{
		List<LMMCareProduct> prodList = productService.getAll(po.getProductId(), po.getProductName(), po.getCityName(), po.getBusinessCode());

		ExportExcelUtils ex=new ExportExcelUtils();
		String codedFileName = null;  
        OutputStream fOut = null;
		//导出头中增加美团及yl
		String[] headers={"产品ID","产品名称","景点名称","城市名称","城市编码","业务类型","更新时间","插入时间","XC名称","XCUrl","TC名称","TCUrl","TN名称","TNUrl","QNR名称","QNRUrl","MT名称","MTUrl"};//业务编码为Ticket
		String[] headers_={"产品ID","产品名称","景点名称","城市名称","城市编码","业务类型","更新时间","插入时间","XC名称","XCUrl","TC名称","TCUrl","TN名称","TNUrl","QNR名称","QNRUrl","MT名称","MTUrl","YL名称","YLUrl"};//业务编码为Hotel
        try {
            // 生成提示信息，  
               response.setContentType("application/vnd.ms-excel");  
            // 进行转码，使其支持中文文件名  
               codedFileName = java.net.URLEncoder.encode("产品url配置", "UTF-8");
               response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xls");
               fOut = response.getOutputStream(); 

               if("HOTEL".equals(po.getBusinessCode())){
				   Field[] fields=getFields(headers_);
				   ex.getHSSFSheet("产品url配置", headers_, fields, prodList, "yyyy-MM-dd");
			   }else{
				   Field[] fields=getFields(headers);
				   ex.getHSSFSheet("产品url配置", headers, fields, prodList, "yyyy-MM-dd");
			   }
               ex.writeToOutput(fOut);
           }
           catch (Exception e) {
               e.printStackTrace();
           }finally {
        	   fOut.close();
		}
		
	}
	
	@RequestMapping("/input")
	@ResponseBody
	public Map<String, Object> inputExcel(MultipartFile  file, HttpServletResponse response, HttpServletRequest request) throws IOException{
		//MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
		//MultipartFile file1 = mRequest.getFile("file");

		Map<String, Object> result=getResult();
		int errorCode=0;
		InputStream is=null;
		try {
			//转换成输入流  
	        is = file.getInputStream();  
	        //得到excel  
	        Workbook workbook = Workbook.getWorkbook(is);
	        //得到sheet  
	        Sheet sheet = workbook.getSheet(0);  
	        //得到列数  
	        int colsNum = sheet.getColumns();
	        //得到行数  
            int rowsNum = sheet.getRows();  
            
            //单元格  
            Cell cell;  
            Map<Integer, String> map = new HashMap<Integer, String>(); 
           
            for (int i = 1; i < rowsNum; i++) {//我的excel第一行是标题,所以 i从1开始  
            	LMMCareProduct cp=new LMMCareProduct();
                for (int j = 0; j < colsNum; j++) {  
                    cell = sheet.getCell(j, i);//注意:第一个参数是列.第二个参数是行  
                    Cell cell0 = sheet.getCell(j, 0);
                    if("产品ID".equals(cell0.getContents())){
                    	cp.setProductId(cell.getContents());
                	}else if("产品名称".equals(cell0.getContents())){
                		cp.setProductName(cell.getContents().trim());
                	}else if("景点名称".equals(cell0.getContents())){
                		cp.setActualName(cell.getContents());
                	}else if("城市名称".equals(cell0.getContents())){
                		cp.setCityName(cell.getContents());
                	}else if("城市编码".equals(cell0.getContents())){
                		cp.setCityCode(cell.getContents());
                	}else if("业务编码".equals(cell0.getContents())){
                		cp.setBusinessCode(cell.getContents());
                	}else if("XC名称".equals(cell0.getContents())){
                		cp.setXc_name(cell.getContents());
                	}else if("XCUrl".equals(cell0.getContents())){
                		cp.setXc_url(cell.getContents());
                	}else if("TC名称".equals(cell0.getContents())){
                		cp.setTc_name(cell.getContents());
                	}else if("TCUrl".equals(cell0.getContents())){
                		cp.setTc_url(cell.getContents());
                	}else if("TN名称".equals(cell0.getContents())){
                		cp.setTn_name(cell.getContents());
                	}else if("TNUrl".equals(cell0.getContents())){
                		cp.setTn_url(cell.getContents());
                	}else if("QNR名称".equals(cell0.getContents())){
                		cp.setQnr_name(cell.getContents());
                	}else if("QNRUrl".equals(cell0.getContents())){
                		cp.setQnr_url(cell.getContents());
                	}
                	//新增美团
					else if("MT名称".equals(cell0.getContents())){
                		cp.setMt_name(cell.getContents());
					}else if("MTUrl".equals(cell0.getContents())){
						cp.setMt_url(cell.getContents());
					}else if("YL名称".equals(cell0.getContents())){
						cp.setYl_name(cell.getContents());
					}else if("YLUrl".equals(cell0.getContents())){
						cp.setYl_url(cell.getContents());
					}else if(Constant.YWLX.equals(cell0.getContents())){//增加业务类型
						cp.setBusinessCode(cell.getContents());
					}
                    map.put(j, cell.getContents());  
                }
				//若导入的模板中不传入业务类型，忽略本条信息
				if(null==cp.getBusinessCode()||"".equals(cp.getBusinessCode())){
					continue;
				}

                //productId不为空则进行操作 为空不进行任何操作
                if(cp.getProductId()!=null&&!"".equals(cp.getProductId().trim())&&
                		cp.getProductName()!=null&&!"".equals(cp.getProductName())&&
                		cp.getCityCode()!=null&&!"".equals(cp.getCityCode())){
					 LMMCareProduct isExists = productService.selectByPrimaryKey(cp.getProductId());
                	 if(isExists!=null && cp.getBusinessCode().equals(isExists.getBusinessCode())){//productid相同执行更新
						//同时判断当前传入的业务类型是否与原来的业务类型相同，不相同则不做任何操作
                     	productService.updateByPrimaryKeySelective(cp);
                     }else if(isExists!=null && !cp.getBusinessCode().equals(isExists.getBusinessCode())){//原来数据库中存在对应产品ID，但导入数据的业务类型与
                     	continue;
                     }else {
						 productService.insertSelective(cp);//productid不同执行插入
					 }
                }else{
                	errorCode=1;
                }
               
            }  
            is.close();
	        
		} catch (Exception e) {
			// TODO Auto-generated catch block
			is.close();
			errorCode=2;
		}finally{
			is.close();
		}
		if(errorCode==1){
			result.put("inputError","产品ID、产品名称和城市编号不能为空，导入失败！");
		}else if(errorCode==0){
			result.put("inputSuccess","数据导入成功！");
		}else{
			result.put("inputError","数据格式不正确，请重新导入");
		}
		return result;
	}
	
	
    /**
     * 根据每列字段名称创建需要导出字段的数组
     * @param headers
     * @return
     */
    public Field[] getFields(String[] headers) {
        Field[] fields=new Field[headers.length];
        LMMCareProduct t=new LMMCareProduct();
        try {
            for(int i=0;i<headers.length;i++){
                if(headers[i].equals("产品ID")){
                    fields[i]=t.getClass().getDeclaredField("productId");
                }else if(headers[i].equals("产品名称")){
                    fields[i]=t.getClass().getDeclaredField("productName");
                }else if(headers[i].equals("景点名称")){
                    fields[i]=t.getClass().getDeclaredField("actualName");
                }else if(headers[i].equals("城市名称")){
                    fields[i]=t.getClass().getDeclaredField("cityName");
                }else if(headers[i].equals("城市编码")){
                    fields[i]=t.getClass().getDeclaredField("cityCode");
                }else if(headers[i].equals("业务编码")){
                    fields[i]=t.getClass().getDeclaredField("businessCode");
                }else if(headers[i].equals("XC名称")){
                    fields[i]=t.getClass().getDeclaredField("xc_name");
                }else if(headers[i].equals("XCUrl")){
                    fields[i]=t.getClass().getDeclaredField("xc_url");
                }else if(headers[i].equals("TC名称")){
                    fields[i]=t.getClass().getDeclaredField("tc_name");
                }else if(headers[i].equals("TCUrl")){
                    fields[i]=t.getClass().getDeclaredField("tc_url");
                }else if(headers[i].equals("TN名称")){
                    fields[i]=t.getClass().getDeclaredField("tn_name");
                }else if(headers[i].equals("TNUrl")){
                    fields[i]=t.getClass().getDeclaredField("tn_url");
                }else if(headers[i].equals("QNR名称")){
                    fields[i]=t.getClass().getDeclaredField("qnr_name");
                }else if(headers[i].equals("QNRUrl")){
                    fields[i]=t.getClass().getDeclaredField("qnr_url");
                }else if(headers[i].equals("更新时间")){
                    fields[i]=t.getClass().getDeclaredField("updateTime");
                }else if(headers[i].equals("插入时间")){
                    fields[i]=t.getClass().getDeclaredField("insertTime");
                }
                //新增美团
				else if(headers[i].equals("MT名称")){
					fields[i]=t.getClass().getDeclaredField("mt_name");
				}else if(headers[i].equals("MTUrl")){
					fields[i]=t.getClass().getDeclaredField("mt_url");
				}else if("YL名称".equals(headers[i])){
					fields[i]=t.getClass().getDeclaredField("yl_name");
				}else if("YLUrl".equals(headers[i])){
					fields[i]=t.getClass().getDeclaredField("yl_url");
				}else if(Constant.YWLX.equals(headers[i])){
					fields[i]=t.getClass().getDeclaredField("businessCode");//增加对业务类型的解析
				}
            }
            
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return fields;
    }
	
	public Map<String, Object> getResult() {
    	
        Map<String, Object> result = new HashMap<String, Object>();
        
        return result;
    }
}
